﻿using PasswdTool.Model;
using PasswdTool.SM4;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Tables;

namespace PasswdTool
{
    public class GlobalContainer
    {
        public static UserModel CurrentUser { get; set; }
        
        public static UserTable UserTable { get; set; }

        public static PasswdTable PasswdTable { get; set; }
        public static readonly string userTable = "userTable.pt";
        public static readonly string passwdTable = "passwdTable.pt";
        private static readonly string fileKey = "1234567890abcdef";
        private static readonly string fileIv = "1234567890abcdef";

        public static bool IsExists(string path)
        {
            return File.Exists(path);
        }

        public static void Serialize(string path,DataTable dt)
        {
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(ms, dt);
                    byte[] data = ms.ToArray();
                    Sm4Crypt sm4Crypt = new Sm4Crypt()
                    {
                        Key = Encoding.UTF8.GetBytes(fileKey),
                        Iv = Encoding.UTF8.GetBytes(fileIv),
                    };
                    data = sm4Crypt.EncryptECB(data).Data;
                    fs.Write(data, 0, data.Length);
                }
            }
        }

        public static DataTable Deserialize(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                if (fs.Length == 0)
                {
                    return null;
                }
                Sm4Crypt sm4Crypt = new Sm4Crypt()
                {
                    Key = Encoding.UTF8.GetBytes(fileKey),
                    Iv = Encoding.UTF8.GetBytes(fileIv),
                };
                byte[] data = new byte[fs.Length];
                fs.Read(data,0,data.Length);
                data = sm4Crypt.DecryptECB(data).Data;
                using (MemoryStream ms = new MemoryStream(data))
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    DataTable dt = (DataTable)bf.Deserialize(ms);
                    return dt;
                }
            }
        }
    }
}
